package com.putong35.common.web.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.putong35.common.R;
import com.putong35.common.baseactfrag.fragment.BaseFragment;
import com.putong35.common.web.ActivityResultTransferable;
import com.putong35.common.web.CommonWebview;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用的WebviewFragment
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2016-09-09
 * @Version: 1.0.0
 */
public class CommonWebviewFragment extends BaseFragment {
    private CommonWebview mWebView;
    private static final String KEY_URL = "URL";
    private String mUrl;
    private Map<String, Object> mJspInterfaceMap = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        if (getArguments() != null) {
            mUrl = getArguments().getString(KEY_URL);
        }
        initWebView();
        mWebView.loadUrl(mUrl);
        Log.e("vivi", "  mWebView.loadUrl(mUrl);   " + mUrl);
        return view;
    }


    public static CommonWebviewFragment newInstance(String url) {
        Bundle args = new Bundle();
        args.putString(KEY_URL, url);
        CommonWebviewFragment fragment = new CommonWebviewFragment();
        fragment.setArguments(args);
        return fragment;
    }

    protected void initWebView() {
        mWebView.init(this);
        // addJavascriptInterface
        addJavascriptInterface(new MobileFunImpl(this), "WebAppJS");//mobile 是与前端定义的一个方法协议
    }

    public WebView getWebview() {
        return mWebView;
    }

    @SuppressLint("JavascriptInterface")
    protected void addJavascriptInterface(Object obj, String name) {
//        mWebView.addJavascriptInterface(new MobileFunImpl(this), "WebAppJS");//mobile 是与前端定义的一个方法协议
        mWebView.addJavascriptInterface(obj, name);
        mJspInterfaceMap.put(name, obj);

    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_common_webview, null);
        mWebView = (CommonWebview) view.findViewById(R.id.webView);
        return view;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 转发给webview
        mWebView.onActivityResult(requestCode, resultCode, data);

        // 转发给JspInterface对象
        for (Map.Entry<String, Object> entry : mJspInterfaceMap.entrySet()) {
            if(entry.getValue() instanceof ActivityResultTransferable) {
                ActivityResultTransferable art = (ActivityResultTransferable) entry.getValue();
                art.onActivityResult(requestCode, resultCode, data);
            }
        }
    }

  /*  //region   业务逻辑模块，填如js接口对象中


    *//**
     * eventbus 登录成功后调用该方法回调web
     *
     * @param event
     *//*
    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onLogin(ClassEvent.WebEvent event) {
        mWebView.loadUrl("javascript:onLogin()");
    }


    private void clipImage(String url, String outputUrl) {
        mFilename = "/" + System.currentTimeMillis() + ".png";
        PhotoActionHelper.clipImage(getActivity())
                .input(url)
                .output(outputUrl + mFilename)
                .maxOutputWidth(320)
                .requestCode(REQUEST_CLIP)
                .start(this);
    }

    @Override
    public void btnPictureClick() {
        Intent intent_TP = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageUri = TakePhoto.getInstance().getOutputMediaFileUri(getActivity().getBaseContext());
        intent_TP.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        startActivityForResult(intent_TP, TAKE_PHOTO_REQUEST);
    }


    @Override
    public void btnPhotoClick() {
        Intent intentPickPhoto = new Intent(getActivity(), SelectAlbumActivity.class);
        intentPickPhoto.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
        intentPickPhoto.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, 1);
        startActivityForResult(intentPickPhoto, SELECT_ALBUM_REQUEST);
    }

    @Override
    public void setTabBar(final int isShow) {
        try {
            final Fragment fragment = getParentFragment();
            fragment.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RadioGroup rgBottomMenu = (RadioGroup) fragment.getActivity().findViewById(com.pachong.android.framework.R.id.rg_bottom);
                    rgBottomMenu.setVisibility(isShow);
                    View view = fragment.getActivity().findViewById(com.pachong.android.framework.R.id.vp_home);
                    view.requestLayout();
                    view.invalidate();
                }
            });

        } catch (NullPointerException e) {
            Log.e("kyluzoi", "can't not findViewByid with tab");
        }
    }

    //endregion */

/*
    @Override
    public View createEmptyInvalidNetView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.empty_invalid_net, null);
        view.findViewById(R.id.btnRefresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.reload();
                setState(CompState.EMPTY_REFRESHING);
            }
        });
        return view;
    }


    @Override
    public View createEmptyRefreshingView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.empty_refreshing, null);
    }*/
}
